package com.huashi.codeUtil;


import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 编码工具类
 */
public class CodecUtil {

    public CodecUtil(){
    }

    public static String encodeBase64(String key) throws UnsupportedEncodingException {
        Base64 base64 = new Base64();
        return base64.encodeToString(key.getBytes(StandardCharsets.UTF_8));
    }

    public static String decodeBase64(String key){
        Base64 base64 = new Base64();
        byte[] decode = base64.decode(key.getBytes());
        return new String(decode);
    }

    public static String encodeHex(String key) throws UnsupportedEncodingException{
        return Hex.encodeHexString(key.getBytes(StandardCharsets.UTF_8));
    }

    public static String decodeHex(String key) throws DecoderException{
        byte[] decodeHex = Hex.decodeHex(key.toCharArray());
        return null != decodeHex ? new String(decodeHex) : "";
    }

    public static String encodeMD5(String key) throws UnsupportedEncodingException{
        return DigestUtils.md5Hex(key.getBytes(StandardCharsets.UTF_8));
    }

    public static String encodeSha1(String key) throws UnsupportedEncodingException{
        return DigestUtils.sha1Hex(key.getBytes(StandardCharsets.UTF_8));
    }
}
